import styles from './index.less';
import './position.less';
import ScaleContainer from '@/components/ScaleContainer/index';
import {
  _getObjBoxFishpondDevices,
  _getObjBoxInfo,
  _openOrCloseSwitch,
} from '@/api/sysUser';
import {
  _getVideoCondition,
  _getObjDeviceVideos,
  _getDataDeviceAlarmList,
  _getDataScheduleTaskAlarmList,
  _getDataBoxPushAlarmList,
  _getMapInBox,
  _getMapBaseTasks,
  _getMapFishBoxes,
  _getNewAlarmInfo,
  _getMapMicro,
  _startObjDeviceVideo,
} from '@/api/baseCondition';

import { useEffect, useState, useRef, useMemo } from 'react';
import { getUserInfo, isFullscreen } from '@/utils';
import { Modal, message, Button } from 'antd';
import {
  ExclamationCircleFilled,
  UpCircleOutlined,
  DownCircleOutlined,
  LeftCircleOutlined,
  RightCircleOutlined,
} from '@ant-design/icons';
import { isEqual } from 'lodash';
const { confirm } = Modal;
import { history } from 'umi';
import Select from '../Home/components/Select';
import VideoM3u8V from './components/VideoM3u8V';
import XinHao from './components/XinHao';
import YinShuiQu from './components/YinShuiQu';
import KpaiCheng from './components/KpaiCheng';
import TpaiCheng from './components/TpaiCheng';
import TimeNow from './components/TimeNow';
import JinShuiKongzhi from './components/JinShuiKongzhi';
import { TaskStatus, AlarmStatus } from '@/constant';
import { set } from 'video.js/dist/types/tech/middleware';

export default function IndexPage() {
  const refEle = useRef(null);
  const [mapInBox, setMapInBox] = useState<any>([]); //进水控制箱数据(信号池数据、引水渠数据)
  const [mapBaseTasks, setMapBaseTasks] = useState<any>([]); //获取基地排程详情(信号池数据、引水渠数据)
  const [goinObj, setGoinObj] = useState<any>({}); //进水控制箱
  const [putOutObj, setPutOutObj] = useState<any>({}); //尾水控制箱
  const [fishArry, setFishArry] = useState<any>([]); //鱼池
  const [isDlog, setIsDlog] = useState<boolean>(false); //信息框
  const [dlogObj, setDlogObj] = useState<any>([]); //信息框对象
  const [dlogName, setDlogName] = useState<string>(''); //信息框对象
  const [zyj, setZyj] = useState<any>({}); //信息框增氧机对象
  const [isClog, setIsClog] = useState<boolean>(false); //确定框
  const [clogObj, setClogObj] = useState<any>({}); //确定框对象
  const [videoCondition, setVideoCondition] = useState<any>([]); //全部摄像头
  const [playObj, setPlayObj] = useState<any>({}); //当前摄像头
  const [isVideo, setIsVideo] = useState<boolean>(false); //视频框
  const [alarmList, setAlarmList] = useState<any>([]); //告警
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false); //告警框
  const [alarmObj, setAlarmObj] = useState<any>({}); //告警信息
  const [micro, setMicro] = useState<any>([]); //微滤机
  const getObjBoxInfo = () => {
    _getObjBoxInfo({ id: 13 }).then((res) => {
      if (res.code == 200) {
        setGoinObj(res.data);
      }
    });
    _getObjBoxInfo({ id: 14 }).then((res) => {
      if (res.code == 200) {
        setPutOutObj(res.data);
      }
    });
  };
  const getObjBoxFishpondDevices = () => {
    const rightIcon = [
      '12-s17',
      '11-s17',
      '10-s17',
      '9-s17',
      '8-s17',
      '7-s17',
      '7-s16',
      '5-s17',
    ];
    _getMapFishBoxes({
      id: history.location.query?.baseId || 1,
    }).then((res) => {
      if (res.code == 200) {
        const newItems = res.data.map((item: any) => {
          const nItems = item.valves.map((i: any) => {
            const str = `${item.id}-${i.attributeCode}`;
            return {
              ...i,
              left: rightIcon.includes(str),
            };
          });
          return {
            ...item,
            valves: nItems,
          };
        });
        setFishArry(newItems);
      }
    });
  };

  const openOrCloseSwitch = () => {
    let item = clogObj;
    _openOrCloseSwitch({
      attributeCode: item.attributeCode,
      deviceCode: item.deviceCode,
      status: item.deviceStatus == 1 ? 0 : 1,
      type: 0,
    }).then((res) => {
      if (res.code == 200) {
        getObjBoxFishpondDevices();
        getObjBoxInfo();
        setClogObj({});
        setIsClog(false);
        message.success(res.msg);
      }
    });
  };
  /**
   * 获取全部摄像头
   */
  const getVideoCondition = async () => {
    // const res = await _getVideoCondition({
    //   baseId: history.location.query?.baseId || 1,
    //   companyId: history.location.query?.companyId || 1,
    // });
    // if (res.code === 200) {
    //   let newData = res.data?.map((item: any) => {
    //     return {
    //       ...item,
    //       value: item.id,
    //       label: item.name,
    //     };
    //   });
    //   setPlayObj(newData[0]?.id ? newData[0] : {});
    //   setVideoCondition(newData);
    // }
    const res = await _getObjDeviceVideos({
      id: history.location.query?.baseId || 1,
      companyId: history.location.query?.companyId || 1,
    });
    if (res.code === 200) {
      console.log(res);
      let newData = res.data?.map((item: any) => {
        return {
          ...item,
          value: item.id,
          label: item.name,
        };
      });
      setPlayObj(newData[0]?.id ? newData[0] : {});
      setVideoCondition(newData);
    }
  };
  const startObjDeviceVideo = async (type: number) => {
    const res = await _startObjDeviceVideo({
      id: playObj.id,
      type: type,
    });
    if (res.code === 200) {
      message.success(res.msg);
    }
  };

  /**
   * 获取报警记录
   */
  const getDataDeviceAlarmList = async () => {
    if (history.location?.query?.type == '1') {
      return;
    }
    const res = await _getNewAlarmInfo({
      id: history.location.query?.baseId || 1,
    });
    if (res.code == 200) {
      let dataObjs = res.data;
      if (dataObjs.content && dataObjs.time) {
        setAlarmObj((oldData: any) => {
          if (
            isEqual(
              {
                content: oldData.content,
                time: oldData.time,
                type: oldData.type,
              },
              dataObjs,
            )
          ) {
            if (oldData.oldTime) {
              let nowTime = Date.now();
              if (nowTime - oldData.oldTime > 18000) {
                //如果
                dataObjs.show = true;
                return dataObjs;
              } else {
                dataObjs.show = false;
                dataObjs.oldTime = new Date();
                return dataObjs;
              }
            } else {
              dataObjs.show = true;
              return dataObjs;
            }
          } else {
            dataObjs.show = true;
            return dataObjs;
          }
        });
        setIsModalOpen(true);
      } else {
        setAlarmObj({});
      }
    }
  };
  /**
   * 获取进水控制箱数据
   */
  const getMapInBox = async () => {
    const res = await _getMapInBox({
      id: history.location.query?.baseId || 1,
    });
    if (res.code === 200) {
      setMapInBox(res.data);
    }
  };
  /**
   * 获取进水控制箱数据
   */
  const getMapBaseTasks = async () => {
    const res = await _getMapBaseTasks({
      id: history.location.query?.baseId || 1,
    });
    if (res.code === 200) {
      setMapBaseTasks(res.data);
    }
  };
  /**
   * 获取微滤机数据
   */
  const getMapMicro = async () => {
    const res = await _getMapMicro({
      id: history.location.query?.baseId || 1,
    });
    if (res.code === 200) {
      setMicro(res.data);
    }
  };

  const kzxStatus = (state: any) => {
    //控制箱状态
    let str = '';
    switch (state) {
      case '0': //离线
        str = 'kzx3.png';
        break;
      case '1': //在线
        str = 'kzx1.png';
        break;
      case '2': //故障
        str = 'kzx5.png';
        break;
      default:
        str = 'kzx1.png';
        break;
    }
    return str;
  };
  const fishNumber = (num: string) => {
    //获取鱼池编号SS1-1  return 1
    return num.substr(-1);
  };
  const ycStatus = (item: any, i: any) => {
    let zyj = '';
    if (item.aeratorStatus == 1) {
      zyj = 'yc.gif';
    } else {
      zyj = 'zyj.png';
    }
    let itemIndex = item?.numericalDevices?.findIndex(
      (element: any) => element.deviceName == '溶解氧',
    );
    console.log(itemIndex);
    return (
      <div
        className={
          item.fishpondName == 'SS2-4' ||
          item.fishpondName == 'SS2-5' ||
          item.fishpondName == 'SS2-6' ||
          item.fishpondName == 'SS2-7' ||
          i.id == 7
            ? styles.ycBo
            : styles.ycBox
        }
      >
        <img className={styles.ycbg} src={require('@/assets/indexbg/yc.png')} />
        <div className={styles.yuChiS}>
          <div className={itemIndex > -1 ? styles.acColor : null}>
            <p className={itemIndex > -1 ? styles.yucNum1 : styles.yucNum}>
              <span className={styles.bianhao}>
                {fishNumber(item.fishpondName)}
              </span>
              <span style={{ fontWeight: 'bold', fontSize: 18 }}>
                {item.fishNum}
              </span>
              <span style={{ fontSize: 10 }}>条</span>
            </p>
            {item?.numericalDevices?.map((i: any) => {
              return (
                <p className={styles.yucList}>
                  {i.deviceName}:
                  <span style={{ fontWeight: 'bold', fontSize: 17 }}>
                    {' '}
                    {i.realDataConvert}
                  </span>
                  <span style={{ fontSize: 12 }}> {i.unit}</span>
                </p>
              );
            })}
            <p className={styles.yucList}>
              执行：
              <span style={{ color: '#4CFA60', fontWeight: 'bold' }}>
                {TaskStatus[item.taskStatus]}
              </span>
            </p>
          </div>
        </div>
        <img className={styles.ycZyj} src={require(`@/assets/${zyj}`)} alt="" />
      </div>
    );
  };
  const sfStatus = (left: any, state: any) => {
    let str = left ? 'r' : 'l';
    if (state == 0) {
      str = str + '3.png';
    } else if (state == 1) {
      str = str + '1.png';
    } else if (state == 2) {
      str = str + '2.png';
    } else if (state == 3) {
      str = str + '4.png';
    } else {
      str = str + '5.png';
    }
    return str;
  };
  const PlayVideoM3u8V = useMemo(() => {
    return <VideoM3u8V playObj={playObj} />;
  }, []);
  useEffect(() => {
    sessionStorage.setItem('sureAlarmList', '[]');
    getDataDeviceAlarmList();
    getObjBoxFishpondDevices();
    getMapInBox();
    getMapBaseTasks();
    getVideoCondition();
    getMapMicro();
    let timer: any = setInterval(() => {
      getObjBoxFishpondDevices();
      getDataDeviceAlarmList();
      getMapInBox();
      getMapBaseTasks();
      getMapMicro();
    }, 60000);
    return () => {
      clearInterval(timer);
      timer = null;
    };
  }, []);
  useEffect(() => {
    if (!isFullscreen()) {
      if (history.location?.query?.type == '1') {
        return;
      }
      confirm({
        title: '全屏',
        icon: <ExclamationCircleFilled />,
        content: '全屏效果更好哦，是否全屏',
        cancelText: '取消',
        okText: '确定',
        onOk() {
          let ele: any = document.body;
          if (ele.requestFullscreen) {
            ele.requestFullscreen();
          } else if (ele.mozRequestFullScreen) {
            ele.mozRequestFullScreen();
          } else if (ele.webkitRequestFullscreen) {
            ele.webkitRequestFullscreen();
          } else if (ele.msRequestFullscreen) {
            ele.msRequestFullscreen();
          }
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }
  }, []);
  return (
    <div className={styles.page}>
      <ScaleContainer width={1920} height={1080}>
        <div>
          <img
            className={styles.bgImg}
            src={require('@/assets/indexbg/bj.png')}
            alt=""
          />
          <div>
            <p className={styles.kzx8}>SS8</p>
            <p className={styles.kzx7}>SS7</p>
            <p className={styles.kzx6}>SS6</p>
            <p className={styles.kzx5}>SS5</p>
            <p className={styles.kzx4}>SS4</p>
            <p className={styles.kzx3}>SS3</p>
            <p className={styles.kzx2}>SS2</p>
            <p className={styles.kzx1}>SS1</p>
            {fishArry?.map((item: any) => {
              const kzxSrc = kzxStatus(item.deviceStatus);
              return (
                <div className={`kzxList kzxList${item.id}`} key={item.id}>
                  <img
                    style={{ width: '74px', height: '90px' }}
                    src={require(`@/assets/index/${kzxSrc}`)}
                    alt=""
                  />
                  <div className="valveListBox">
                    {item.valves?.map((ite: any) => {
                      const sfSrc = sfStatus(ite.left, ite.deviceStatus);
                      return (
                        <div key={ite.attributeCode}>
                          <div
                            onClick={() => {
                              setClogObj(ite);
                              setIsClog(true);
                            }}
                            className={`valveListBoxItem valveListBoxItem${item.id}${ite.attributeCode}`}
                          >
                            <img
                              className={styles.kgimgs}
                              src={require(`@/assets/index/${sfSrc}`)}
                              alt=""
                            />
                          </div>
                        </div>
                      );
                    })}
                    {item.fishponds?.map((it: any) => (
                      <div
                        key={it.fishpondName}
                        className={`fishpondListItem fishpondListItem${it.fishpondName}`}
                      >
                        {ycStatus(it, item)}
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}

            <div
              onClick={() => {
                setPlayObj(videoCondition[0]);
                setIsVideo(true);
              }}
              className={styles.sxt0}
            >
              <div className={styles.sxtv}>1</div>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[2]);
                setIsVideo(true);
              }}
              className={styles.sxt1}
            >
              <div className={styles.sxtv}>2</div>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[9]);
                setIsVideo(true);
              }}
              className={styles.sxt2}
            >
              <div className={styles.sxtv}></div>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[8]);
                setIsVideo(true);
              }}
              className={styles.sxt3}
            >
              <div className={styles.sxtv}></div>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[7]);
                setIsVideo(true);
              }}
              className={styles.sxt4}
            >
              <div className={styles.sxtv}></div>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[4]);
                setIsVideo(true);
              }}
              className={styles.sxt5}
            >
              <div className={styles.sxtv}></div>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[6]);
                setIsVideo(true);
              }}
              className={styles.sxt6}
            >
              <div className={styles.sxtv}></div>
            </div>
            {isVideo ? (
              <div className={styles.videoBox}>
                <div className={styles.videoTitles}>
                  <div className={styles.videoTitle}>视频监控</div>
                  <div className={styles.select}>
                    <Select
                      widthName={300}
                      onChange={(e: any) => {
                        setPlayObj(e);
                      }}
                      ac={playObj ? playObj : videoCondition[0]}
                      op={videoCondition}
                    />
                  </div>
                </div>
                <div className={styles.videobox}>
                  <VideoM3u8V playObj={playObj} />
                  <UpCircleOutlined
                    onClick={() => {
                      startObjDeviceVideo(21);
                    }}
                    className={styles.upCircleOutlined}
                  />
                  <DownCircleOutlined
                    onClick={() => {
                      startObjDeviceVideo(22);
                    }}
                    className={styles.downCircleOutlined}
                  />
                  <LeftCircleOutlined
                    onClick={() => {
                      startObjDeviceVideo(23);
                    }}
                    className={styles.LeftCircleOutlined}
                  />
                  <RightCircleOutlined
                    onClick={() => {
                      startObjDeviceVideo(24);
                    }}
                    className={styles.RightCircleOutlined}
                  />
                </div>
                <img
                  className={styles.closeImg}
                  onClick={() => {
                    setIsVideo(false);
                  }}
                  src={require('@/assets/close.png')}
                  alt=""
                />
              </div>
            ) : null}
            {alarmObj.show ? (
              <Modal
                width={420}
                wrapClassName={'alarmBoxa'}
                footer={
                  <Button
                    onClick={() => {
                      setAlarmObj({
                        ...alarmObj,
                        oldTime: Date.now(),
                      });
                      setIsModalOpen(false);
                    }}
                    type="primary"
                  >
                    确定
                  </Button>
                }
                title={AlarmStatus[alarmObj.type]}
                open={isModalOpen}
                onCancel={() => {
                  setAlarmObj({
                    ...alarmObj,
                    oldTime: Date.now(),
                  });
                  setIsModalOpen(false);
                }}
                okText="确定"
                cancelText={null}
              >
                <div className={styles.alarmBox}>
                  <img
                    className={styles.alarmImg}
                    src={require('@/assets/alrm.png')}
                    alt=""
                  />
                  <h3 className={styles.alarmText}>{alarmObj.content}</h3>
                </div>
              </Modal>
            ) : null}
            <div className={styles.paicheng}>
              <XinHao data={mapInBox?.inPoolNumericals} />
            </div>
            <div className={styles.jinshuikongzhi}>
              <JinShuiKongzhi data={mapInBox?.inBoxNumericals} />
            </div>
            <div className={styles.yinshuiqu}>
              <YinShuiQu data={mapInBox?.inCanalNumericals} />
            </div>
            <div className={styles.kpaicheng}>
              <KpaiCheng data={mapBaseTasks?.boxTasks} />
            </div>
            <div className={styles.tpaicheng}>
              <TpaiCheng data={mapBaseTasks?.feedTasks} />
            </div>
            <div className={styles.timeNow}>
              <TimeNow />
            </div>
            <div className={styles.wlj}>
              <img
                className={styles.wljBg}
                src={require('@/assets/index/wlj.png')}
                alt=""
              />
              <div className={styles.wljStatus}>
                {micro.map((item: any) => {
                  console.log(item);
                  let wljClassName = '';
                  if (item.deviceStatus == 0) {
                    wljClassName = 'wljS0';
                  } else if (item.deviceStatus == 1) {
                    wljClassName = 'wljS1';
                  } else {
                    wljClassName = 'wljS2';
                  }
                  return <div className={`${wljClassName}`}></div>;
                })}
              </div>
            </div>
          </div>
        </div>
      </ScaleContainer>
    </div>
  );
}
